/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function parseChiefComplaint(chiefComplaint, dictIndex) {
  if (!chiefComplaint) {
    return ''
  }
  let arr = []
  chiefComplaint.data.forEach(e => {
    let str = ''
    if (e.chosen) {
      str += parseChiefComplaintItem(e, dictIndex)
      if (e.follow && e.follow.length > 0) {
        str += '&nbsp;伴随:&nbsp;'
        let fArr = []
        e.follow.forEach(f => {
          fArr.push(parseChiefComplaintItem(f, dictIndex))
        })
        str += fArr.join('&nbsp;&nbsp;')
      }
      arr.push(str)
    }
  })
  return arr.join('<br>')
}
export function parseChiefComplaintItem(e, dictIndex) {
  let str = ''
  // 部位
  if (e.part && e.part.length > 0) {
    str += e.part.map(p => dictIndex.complex.DTMPartType010[p]).join('')
  }
  // 程度
  if (e.level) {
    str += dictIndex.simple.DTMCC040[e.level]
  }
  // 性质
  if (e.character) {
    str += dictIndex.simple.DTMCC030[e.character]
  }
  // 症状
  if (e.symptom) {
    str += dictIndex.simple.DTMCC020[e.symptom]
  }
  // 时间
  if (e.time) {
    str += e.time + dictIndex.simple.DTMCC050[e.unit]
  }
  return str
}
/*
export function parseChiefComplaint(chiefComplaint, dictIndex) {
  if (!chiefComplaint) {
    return ''
  }
  let str = ''
  chiefComplaint.data.forEach(e => {
    if (e.chosen) {
      str += Object.values(parseChiefComplaintItem(e, dictIndex)).filter(e => e).join('、')
      if (e.follow && e.follow.length > 0) {
        str += '&nbsp;伴随:&nbsp;'
        e.follow.forEach(fe => {
          str += Object.values(parseChiefComplaintItem(fe, dictIndex)).filter(e => e).join('、')
        })
      }
      str += '&nbsp;&nbsp;&nbsp;&nbsp;'
    }
  })
  return str
}

export function parseChiefComplaintItem(e, dictIndex) {
  let _e
  _e = JSON.parse(JSON.stringify(e))
  if (e.time) {
    _e.time = _e.time + dictIndex.simple.DTMCC050[_e.unit]
  }
  if (e.part) {
    _e.part = _e.part.map(a => dictIndex.complex.DTMPartType010[a]).join('-')
  }
  delete _e['unit']
  delete _e['chosen']
  delete _e['changing']
  delete _e['_id']
  delete _e['follow']
  delete _e['showKeyboard']
  _e.level = dictIndex.simple.DTMCC040[_e.level]
  _e.character = dictIndex.simple.DTMCC030[_e.character]
  _e.symptom = dictIndex.simple.DTMCC020[_e.symptom]
  return _e
}
*/
export function parseHPI(HPI, dictIndex) {
  let str = '目前情况:&nbsp;&nbsp;'
  if (HPI.situation.ifNull) {
    str += '无'
  } else {
    str += '发病日期:' + HPI.situation.date + '&nbsp;&nbsp;诱因:' + HPI.situation.cause.map(e => dictIndex.simple.DTMPI010[e]).join(',')
  }
  str += '&nbsp;&nbsp;检查化验:'
  if (HPI.unusual.ifNull) {
    str += '无'
  } else {
    HPI.unusual.data.forEach(e => {
      e.data.forEach(j => {
        str += j.itemName + ':' + j.resultValue + '&nbsp;&nbsp;'
      })
    })
  }
  str += '&nbsp;&nbsp;治疗情况:'
  if (HPI.treatment.ifNull) {
    str += '无'
  } else {
    HPI.treatment.data.forEach(e => {
      str += `${dictIndex.simple.DTMPI020[e.display]},${dictIndex.simple.DTMPI030[e.method]},`
      if (e.method == 'D.104.100001') {
        str += dictIndex.simple.DTMPI040[e.measure] + ','
      } else if (e.method == 'D.104.100002') {
        str += dictIndex.simple.DTMPI045[e.measure] + ','
      }
      str += `${dictIndex.simple.DTMPI050[e.effect]},${e.duration}${dictIndex.simple.DTMCC050[e.unit]}`
    })
  }
  return str
}
export function parsePastHistory(pastHistory, dictIndex) {
  let str = '个人史: '
  if (pastHistory.personal.data.length > 0) {
    str += pastHistory.personal.data.join(',')
  } else {
    str += '无'
  }
  str += '&nbsp;&nbsp;家庭史:'
  pastHistory.family.data.forEach(e => {
    str += dictIndex.simple.DTMHI130020[e.disease] + ',' + dictIndex.simple.DTMHI130010[e.sibship] + ',' + e.age + '岁&nbsp;&nbsp;'
  })
  str += '过敏史:'
  pastHistory.allergic.data.forEach(e => {
    str += e.source + ',' + dictIndex.simple.DTMHI100020[e.reaction] + ',' + dictIndex.simple.DTMHI100030[e.level] + '&nbsp;&nbsp;'
  })
  str += `月经史:&nbsp;&nbsp;
    初潮年龄:${pastHistory.menstrual.firstAge}
    月经周期:${pastHistory.menstrual.cycle}
    行经天数:${pastHistory.menstrual.duration}
    末次月经日期:${pastHistory.menstrual.lastDate}
    闭经日期:${pastHistory.menstrual.endDate}
    绝经年龄:${pastHistory.menstrual.endAge}岁`
  str += '&nbsp;&nbsp;慢性病史:'
  pastHistory.chronic.data.forEach(e => {
    str += dictIndex.simple.DTMHI195020[e.disease] + e.duration + dictIndex.simple.DTMHI195030[e.durationUnit] + dictIndex.simple.DTMHI195040[e.level]
  })
  return str
}
export function parsePE(pe) {
  let arr = []
  pe.items.small.concat(pe.items.big).forEach(e => {
    if (e.showFlag) {
      if (e.unit) {
        arr.push(e.name + ':' + pe.values[e.code] + e.unit)
      } else {
        arr.push(e.name + ':' + pe.values[e.code])
      }
    }
  })
  return arr.join(',')
}
export function parseCheckout(tempOpen) {
  let HPI = tempOpen.HPI
  let checkout = tempOpen.checkout
  let checked = []
  HPI.unusual.data.forEach(e => {
    e.data.forEach(j => {
      checked.push(j.itemName + ':' + j.resultValue + '&nbsp;&nbsp;')
    })
  })
  if (checkout.checking) {
    checked = checked.concat(checkout.checking.map(e => e.itemName + '(' + e.number + ')' + e.date + (e.urgent ? '加急' : '')))
  }
  if (checkout.testing) {
    checked = checked.concat(checkout.testing.map(e => e.itemName + '(' + e.number + ')' + e.date + (e.urgent ? '加急' : '')))
  }
  return checked.join('&nbsp;,&nbsp;')
  // return checkout.checkingTesting.map(e => e.name + '(' + e.number + ')' + e.date + (e.urgent ? '加急' : '')).join('<br>')
}
export function parseDiagnosis(diagnosis) {
  return diagnosis.map(e => e.diseaseName + (e.state == 'confirm' ? '确诊' : '疑似')).join(',')
}
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}